package com.hibernate.hrm.config.login;

import com.hibernate.hrm.entity.User;
import com.hibernate.hrm.service.login.OperateLogService;
import com.hibernate.hrm.service.login.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.transaction.Transactional;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private final OperateLogService operateLogService;
    private final UserService userService;
    private final HttpServletRequest request;

    public CustomAuthenticationSuccessHandler(OperateLogService operateLogService,
                                              UserService userService,
                                              HttpServletRequest request) {
        this.operateLogService = operateLogService;
        this.userService = userService;
        this.request = request;
    }

    @Override
    @Transactional
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws IOException {
        User user = (User) authentication.getPrincipal();

        // 更新最后登录时间
        userService.updateLastLogin(user.getUserId(), request);

        // 记录登录日志（确保只记录一次）
        operateLogService.recordLoginLog(user.getUserId(), request, true);

        response.sendRedirect("/home");
    }
}
